package com.dongdong.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.dongdong.api.SellerApi;
import com.dongdong.model.TbSeller;
import com.dongdong.vo.SeckillGoodsVO;
import com.dongdong.mapper.TbSeckillGoodsMapper;
import com.dongdong.model.TbSeckillGoods;
import com.dongdong.model.TbSeckillGoodsExample;
import com.dongdong.service.SeckillService;
import com.dongdong.vo.SellerVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private TbSeckillGoodsMapper seckillGoodsMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SellerApi sellerApi;

    @Override
    public void redisHot() {
        TbSeckillGoodsExample example = new TbSeckillGoodsExample();
        Date date = new Date();
        example.createCriteria().andStartTimeLessThanOrEqualTo(date)
                .andEndTimeGreaterThanOrEqualTo(date);
        List<TbSeckillGoods> tbSeckillGoods = seckillGoodsMapper.selectByExample(example);
        tbSeckillGoods.stream().map((x) -> {
            SeckillGoodsVO vo = new SeckillGoodsVO();
            BeanUtils.copyProperties(x, vo);
            return vo;
        }).forEach((y) -> {
            redisTemplate.boundHashOps("dongdongshop:seckill").put(y.getId(),y);
        });


    }

    @Override
    public List<SeckillGoodsVO> getSeckillList() {
        List<SeckillGoodsVO> values = redisTemplate.boundHashOps("dongdongshop:seckill").values();
        return values;
    }


    @SentinelResource("goods")
    public void queryGoods(){
        System.err.println("查询商品");
    }

    @Override
    public SeckillGoodsVO getSecKill(Long id) {
        TbSeckillGoods tbSeckillGoods = seckillGoodsMapper.selectByPrimaryKey(id);
        SeckillGoodsVO vo = new SeckillGoodsVO();
        BeanUtils.copyProperties(tbSeckillGoods,vo);
        TbSeller tbSeller = sellerApi.getSellerByName(vo.getSellerId());
        SellerVO sellerVO = new SellerVO();
        BeanUtils.copyProperties(tbSeller,sellerVO);

        vo.setSellerVO(sellerVO);
        return vo;
    }

    @Override
    public SeckillGoodsVO getSecKillById(Long id) {
        SeckillGoodsVO seckillGoodsVO = (SeckillGoodsVO) redisTemplate.boundHashOps("dongdongshop:seckill").get(id);

        return seckillGoodsVO;
    }

    @Override
    public void updateSeckillGoodsVO(SeckillGoodsVO seckillGoodsVO) {
        TbSeckillGoods seckillGoods = new TbSeckillGoods();
        BeanUtils.copyProperties(seckillGoodsVO,seckillGoods);
        seckillGoodsMapper.updateByPrimaryKeySelective(seckillGoods);
    }
}
